//
//  LoginVM.swift
//  mac-wky
//
//  Created by Apple on 2018/2/8.
//  Copyright © 2018年 Apple. All rights reserved.
//

import Foundation
import Moya
import RxSwift
import RxCocoa

class LoginVM {
    private let provider = MoyaProvider<ApiTarget>()
    
    /// 登录按钮是否可用
    var isLoginEnabled: Driver<Bool>
    var isLogin: Driver<Bool>
    
    init(input: (phoneText: Driver<String>, pwdText: Driver<String>, loginTap: Driver<Void>)) {
        // 登录按钮是否可用
        let isValid_phone = input.phoneText.map { $0.count == 11 }
        let isValid_pwd = input.pwdText.map { $0.count >= 4 }
        
        let login = Variable(false)
        isLogin = login.asDriver()
        
        isLoginEnabled = Driver
            .combineLatest(isValid_phone, isValid_pwd) { $0 && $1 }
            .distinctUntilChanged()
        
        // 登录按钮点击
        let phoneAndPwd =  Driver.combineLatest(input.phoneText, input.pwdText)
        _ = input.loginTap
            .map { App.clearCookie() }  // 清空cookie
            .withLatestFrom(phoneAndPwd)
            .flatMapLatest { phone, pwd -> Driver<LoginRst> in
                return XLoginApi.shared.login(phone: phone, pwd: pwd)
            }
            .drive(onNext: { rst in
                print("\(rst.iRet) : \(rst.sMsg)")
                if rst.iRet == "0" {
                    App.alert("登录成功")
                } else {
                    App.alert(rst.sMsg)
                }
            })
        
    }
    
}
